//引用文件系统模块
var fs = require("fs");
//引用imageinfo模块
var image = require("imageinfo");

function readFileList(path, filesList) {
	var files = fs.readdirSync(path);
	files.forEach(function(itm, index) {
		var stat = fs.statSync(path + itm);
		if(stat.isDirectory()) {
			//递归读取文件
			readFileList(path + itm + "/", filesList)
		} else {

			var obj = {}; //定义一个对象存放文件的路径和名字
			obj.path = path; //路径
			obj.filename = itm //名字
			filesList.push(obj);
		}

	})

}
var getFiles = {
	//获取文件夹下的所有文件
	getFileList: function(path) {
		var filesList = [];
		readFileList(path, filesList);
		return filesList;
	},
	//获取文件夹下的所有图片
	getImageFiles: function(path) {
		var imageList = [];

		this.getFileList(path).forEach((item) => {
			var ms = image(fs.readFileSync(item.path + item.filename));

			ms.mimeType && (imageList.push(item.filename))
		});
		return imageList;
	}
};

//获取文件夹下的所有图片
var imageList = getFiles.getImageFiles("../img/test/");
console.log(imageList)

var WebSocketServer = require('ws').Server,
	wss = new WebSocketServer({
		port: 8181
	});

wss.on('connection', function(ws) {
	console.log('client connected');
	ws.send(JSON.stringify(imageList))
	ws.on('message', function(message) {
		console.log(message);
	});

	var timer = setInterval(function() {
		var index = randomNum(0, imageList.length - 1);
		var img = imageList[index];
		var frameid = randomNum(1,5);
		var obj = {
			path: img,
			id: frameid
		}
		console.log(index, img, obj)
		ws.send(JSON.stringify(obj))
	}, 1000000)

	//	setTimeout(function() {
	//		//		clearInterval(timer)
	//		var index = randomNum(0, imageList.length - 1);
	//		var img = imageList[index];
	//		var obj = {
	//			path: img
	//		}
	//		console.log(index, img, obj)
	//		ws.send(JSON.stringify(obj))
	//	}, 1000)
	ws.on('close', function() {
		clearTimeout(timer);
	});
});

//var imageList = ["img/test/1.jpg","img/test/2.jpg","img/test/3.jpg","img/test/4.jpg","img/test/5.jpg","img/test/6.jpg","img/test/7.jpg","img/test/8.jpg","img/test/9.jpg"]

function randomNum(minNum, maxNum) {
	switch(arguments.length) {
		case 1:
			return parseInt(Math.random() * minNum + 1, 10);
			break;
		case 2:
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
			break;
		default:
			return 0;
			break;
	}
}